package service;

import controller.MainController;
import controller.NewController;
import common.Course;
import common.Message;
import common.MessageType;
import common.User;
import util.FlushCourse;
import util.Warn;

import java.io.ObjectInputStream;
import java.net.Socket;
import java.util.Vector;

public class ClientConnectServer extends Thread{
    private Socket socket;
    private User user;
    public ClientConnectServer(Socket socket,User user){
        this.socket=socket;
        this.user=user;
    }
    @Override
    public void run(){
        //需要一直保持通信
        while(true){
            //一直等待从服务器发送过来的消息
            System.out.println("等待服务器响应");
            try {
                ObjectInputStream ois=new ObjectInputStream(socket.getInputStream());
                //服务器没有发送时，阻塞
                Message ms=(Message) ois.readObject();
                if(ms.getState()==MessageType.new_Fail){
                    Warn.warn("新建失败","课程号已被使用");
                    System.out.println("新建失败");
                }else if(ms.getState()==MessageType.new_Success){
                    System.out.println("新建成功");
                }else if(ms.getState()==MessageType.add_Fail){
                    Warn.warn("添加失败","邀请码无效");
                    System.out.println("添加失败");
                }else if(ms.getState()==MessageType.add_Success){
                    System.out.println("课程添加成功");
                }else if(ms.getState()==MessageType.send_Course){
                    System.out.println("刷新列表");
                    FlushCourse.Flush((Vector<Course>) ois.readObject(),(Vector<Course>) ois.readObject());
                }else if(ms.getState()==MessageType.Stu_Add_Success){
                    System.out.println("添加学生成功");
                }else if(ms.getState()==MessageType.Stu_Add_Fail){
                    System.out.println("添加学生失败");
                    Warn.warn("添加失败","学生不存在/已添加");
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.exit(0);
                break;
            }
        }
    }

    public Socket getSocket() {
        return socket;
    }
}
